from rest_framework import status
from rest_framework.generics import CreateAPIView, RetrieveAPIView, UpdateAPIView
from rest_framework.permissions import IsAuthenticated
from rest_framework.response import Response
from rest_framework.views import APIView
from . import serializers
from users.models import User

# (email-2.1)点击邮箱激活码触发的激活验证视图
class VerifyEmailView(APIView):
    def get(self,request):
        token = request.query_params.get('token')
        if not token:
            return Response({'message': '缺少token'}, status=status.HTTP_400_BAD_REQUEST)

        user = User.check_verify_email_token(token)
        if user is None:
            return Response({'message': '链接信息无效'}, status=status.HTTP_400_BAD_REQUEST)

        user.email_active = True
        user.save()
        print('点击验证链接后验证通过！')
        return Response({'message': 'OK'})



# (email-1.1)点击保存按钮--添加邮件的后端: 用于保存用户的邮箱信息，注意需要用户登录通过认证后
class EmailView(UpdateAPIView):

    # 指定序列化器
    serializer_class = serializers.EmailSerializer
    # 验证用户是否登录
    permission_classes = [IsAuthenticated]

    def get_object(self):
        return self.request.user


# 个人中心
class UserDetailView(RetrieveAPIView):

    serializer_class = serializers.UserDetailSerializer
    permission_classes = [IsAuthenticated]  # RetrieveAPIView提供的验证用户是否登陆的工具

    def get_object(self):
        return self.request.user

'''
用户数量
手机号数量
注册

注意三个视图函数继承的类  APIView ,CreateAPIView
'''
class UsernameCountView(APIView):
    def get(self,request,username):

        count = User.objects.filter(username=username).count()
        data = {
            'count':count,
            'username':username
        }
        return Response(data)


class MobileCountView(APIView):
    def get(self,request,mobile):
        count = User.objects.filter(mobile=mobile).count()
        data = {
            'count':count,
            'mobile':mobile
        }
        return Response(data)


class UserView(CreateAPIView):
    serializer_class = serializers.CreateUserSerializer


# 登陆模块单独出去
# 登陆--Django REST framework JWT提供了登录签发JWT的视图，可以直接使用
# 但是！ 默认返回的只有token，要返回username,user_id,token 需要新建utils模块继承并重写这个类

















